home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / wdiff004.lha / wdiff-0.04 / writepipe.c < prev   
C/C++ Source or Header  |  1992-12-05  |  2KB  |  72 lines

  1. /* Open a pipe to write to a program without intermediary sh.
  2.    Copyright (C) 1992 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by David MacKenzie.  */
  19.  
  20. #include <stdio.h>
  21. #include <varargs.h>
  22.  
  23. #if defined (HAVE_UNISTD_H)
  24. #include <unistd.h>
  25. #endif
  26.  
  27. /* Open a pipe to write to a program without intermediary sh.
  28.    Checks PATH.
  29.    Sample use:
  30.    stream = writepipe ("progname", "arg1", "arg2", (char *) 0);
  31.    Return 0 on error. */
  32.  
  33. /* VARARGS */
  34. FILE *
  35. writepipe (va_alist)
  36.   va_dcl
  37. {
  38.   int fds[2];
  39.   va_list ap;
  40.   char *args[100];
  41.   int argno = 0;
  42.  
  43.   /* Copy arguments into `args'. */
  44.   va_start (ap);
  45.   while ((args[argno++] = va_arg (ap, char *)) != NULL)
  46.     /* Do nothing. */ ;
  47.   va_end (ap);
  48.  
  49.   if (pipe (fds) == -1)
  50.     return 0;
  51.  
  52.   switch (fork ())
  53.     {
  54.     case 0:            /* Child.  Read from pipe. */
  55.       close (fds[1]);        /* Not needed. */
  56.       if (fds[0] != 0)        /* Redirect 0 (stdin) only if needed.  */
  57.     {
  58.       close (0);        /* We don't want the old stdin. */
  59.       dup (fds[0]);        /* Guaranteed to dup to 0 (stdin). */
  60.       close (fds[0]);    /* No longer needed. */
  61.     }
  62.       execvp (args[0], args);
  63.       _exit (2);        /* 2 for `cmp'. */
  64.     case -1:            /* Error. */
  65.       return 0;
  66.     default:            /* Parent.  Write to pipe. */
  67.       close (fds[0]);        /* Not needed. */
  68.       return fdopen (fds[1], "w");
  69.     }
  70.   /* NOTREACHED */
  71. }
  72.